//
//  ListScrollView.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/6/25.
//

import UIKit
import MJRefresh

class ListScrollView: UIScrollView {

    var scrollCanScroll = false
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        contentInsetAdjustmentBehavior = .never
        backgroundColor = .white
        delegate = self
        scrollCanScroll = true
        showsVerticalScrollIndicator = false
        NotificationCenter.default.addObserver(self, selector: #selector(scrollNotification(_:)), name: NSNotification.Name(rawValue: "List_scrollCanScroll"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(scrollHeaderRefreshStop(_:)), name: NSNotification.Name(rawValue: "List_scrollHeaderRefreshStop"), object: nil)
        mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.mj_header?.beginRefreshing()
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "List_tableHeaderRefresh"), object: nil, userInfo: nil)
        })
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "List_scrollCanScroll"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "List_scrollHeaderRefreshStop"), object: nil)
    }
    
}

extension ListScrollView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let maxOffsetY = 0.0
        if scrollView.contentOffset.y >= maxOffsetY {
            scrollView.setContentOffset(CGPoint(x: 0, y: maxOffsetY), animated: false)
            scrollCanScroll = false
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "List_tableCanScroll"), object: nil, userInfo: ["canScroll": "1"])
        } else {
            if !scrollCanScroll {
                scrollView.setContentOffset(CGPoint(x: 0, y: maxOffsetY), animated: false)
            }
        }
    }
}

extension ListScrollView {
    @objc func scrollNotification(_ notification: Notification) {
        let userInfo: NSDictionary = notification.userInfo! as NSDictionary
        let canScroll: String = userInfo["canScroll"] as! String
        if (canScroll as NSString).boolValue {
            scrollCanScroll = true
        }
    }
    
    @objc func scrollHeaderRefreshStop(_ notification: Notification) {
        mj_header?.endRefreshing()
    }
    
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
}

